﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace nwrole.lib2 {
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class OrchestratorService : IOrchestratorContract {
        private List<IOrchestratorClientContract> supervisors = new List<IOrchestratorClientContract>();

        public int NumConnectedSupervisors {
            get { return supervisors.Count; }
        }

        public void RegisterSupervisor() {
            Console.WriteLine("Client connected"); 
            WriteLog("Supervisor connected");
            IOrchestratorClientContract callback = OperationContext.Current.GetCallbackChannel<IOrchestratorClientContract>();

            ICommunicationObject obj = (ICommunicationObject)callback;
            obj.Closed += ClientClosed;
            obj.Closing += ClientClosing;
            obj.Faulted += ClientFaulted;

            int test = callback.GetNumServices();

            supervisors.Add(callback);
        }

        void ClientClosing(object sender, EventArgs e) 
        {
            WriteLog("Supervisor closing");
            Console.WriteLine("Client Closing..."); 
        }

        void ClientClosed(object sender, EventArgs e) {
            WriteLog("Supervisor closed");
            Console.WriteLine("Client closed"); 

            IOrchestratorClientContract callback = ((IOrchestratorClientContract)sender);
            if( supervisors.Contains(callback)) {
                WriteLog("Supervisor client found and removed");
                supervisors.Remove(callback);
            }
        }

        void ClientFaulted(object sender, EventArgs e) {
            WriteLog("Supervisor faulted");

            IOrchestratorClientContract callback = ((IOrchestratorClientContract)sender);
            if (supervisors.Contains(callback)) {
                WriteLog("Supervisor client found and removed");
                supervisors.Remove(callback);
            }
        }

        public void ReportError(string msg) {
            WriteLog("OrchestratorService.ReportError: " + msg);
        }

        private static void WriteLog(string content) {
            DateTime now = DateTime.Now;
            var path = "c:/log/nwrole/Orchestrator/";
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            System.IO.File.AppendAllText(path + "log " + now.ToString("yyyy-MM-dd") + ".txt", now.ToString("yyyy-MM-dd hh:mm:ss ") + content + "\r\n");
        }
    }
}
